package com.hyyt.shopjsp.wxmg.util;

import com.hyyt.shopjsp.util.common.StringStaticKey;
import com.hyyt.shopjsp.util.common.Utils;
import com.hyyt.shopjsp.util.json.FastJsonUtils;
import com.hyyt.shopjsp.util.redis.util.RedisDataReadUtil;
import com.hyyt.shopjsp.wxmg.basicInfo.pojo.WxGlobalReturnCode;
import net.sf.json.JSONObject;

import java.util.List;
import java.util.Map;

/**
 * 全局返回码工具类
 */
public class WxGlobalReturnCodeUtil {

	private static final long serialVersionUID = -8988954502724648636L;

    /**
     * 回复消息
     * @param stringJson
     * @param globalReturnCodeList
     * @return 返回值String 1：true 正确 ，2：错误提示消息
     */
	public static String getGlobalReturnCode(String stringJson, List<WxGlobalReturnCode> globalReturnCodeList) {
		if(Utils.objectIsEmpty(globalReturnCodeList)){
			String publicNoInfoStr = RedisDataReadUtil.getRedisValue(StringStaticKey.WX_PUBLIC_NO_INFO);
			Map<String,Object> publicNoInfo = FastJsonUtils.stringToCollect(publicNoInfoStr);
			String globalReturnCodeStr = RedisDataReadUtil.getRedisValue(StringStaticKey.WX_GLOBAL_RETURN_CODE);
			globalReturnCodeList = FastJsonUtils.toList(globalReturnCodeStr, WxGlobalReturnCode.class);
		}
		JSONObject jo = JSONObject.fromObject(stringJson);
		if(jo.containsKey("created_at")){//上传多媒体
			return "true";
		}else if(jo.containsKey("subscribe")){//得到个人详细信息
			return "true";
		}else if(jo.containsKey("groups")){//查询分组
			return "true";
		}else if(jo.containsKey("access_token")){//得到访问令牌
			return "true";
		}else if(jo.containsKey("groupid")){//查询所在分组Id
			return "true";
		}else if(jo.containsKey("next_openid")){//获得粉丝列表
			return "true";
		}else if("0".equals(jo.getString("errcode"))){//发送客服消息;高级群发;修改分组;
			return "true";
		}else{
			String back = backErrorMessage(jo, globalReturnCodeList);
			return jo.getString("errcode") + back;
		}
	}
	
	//下载判断
	public static String uploadBack(String strJson,List<WxGlobalReturnCode> globalReturnCodeList){//下载上传多媒体
		JSONObject jo = JSONObject.fromObject(strJson);
		if(jo.containsKey("errcode")){
			String back=backErrorMessage(jo,globalReturnCodeList);
			return jo.getString("errcode")+back;
		}else{
			return null;
		}
	}

	//
	public static String backErrorMessage(JSONObject jo, List<WxGlobalReturnCode> globalReturnCodeList){
		for(WxGlobalReturnCode globalReturnCode:globalReturnCodeList){
			if(globalReturnCode.getReturncode().equals(jo.getString("errcode"))){
				//String s = JSONArray.fromObject(globalReturnCode).toString();
				return globalReturnCode.getDiscretion();
			}
		}
		return null;
	}
	
}
